package com.handpay.zztong.hp;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.handpay.zztong.hp.base.activity.BaseActivity;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.swiper.ISwiperListener;
import com.handpay.framework.swiper.SwiperModel;
import com.handpay.framework.swiper.ic.IICSelectApplicationCallback;
import com.handpay.framework.swiper.landi.LandiSwiperBT;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.swiper.widget.SwiperCardVoiceView;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.swiper.widget.SwiperCardBluetoothView;

/**
 * Created by jmshuai on 2014/12/25.
 */
public class SwipeCard extends ZZTongActivity {
    private LinearLayout llContent	= null;
    private SwiperCardBluetoothView mSwiperCardView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        this.setContentView(R.layout.activity_vpos);
        super.onCreate(savedInstanceState);
        //清除factor
        clearFactor();
        //为了防止oem有定制标题主题会在获取卡号界面显示标题栏，特殊处理
        myActionBar.setVisibility(View.GONE);
        llContent = (LinearLayout) this.findViewById(R.id.llContent);
        refreshStatus(ISwiperListener.Status_Swipe);
        if(ApiSwiperFactory.getInstance().getSwiperModel() ==  SwiperModel.M35_BLUETOOTH){
        	LandiSwiperBT.isSwiperCard = true;
        }
        doSwipe();
    }
    
    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    @Override
    public void onSwiperPlugOff() {
        HPLog.i("onSwiperPlugOff", "Go back!");
        onFunctionTab(null);
        goBack();
    }

    /**
     * 刷新状态
     */
    private Handler hRefreshStatus = new VPOSHandler(this);

    /**
     * 只负责显示界面。不做刷卡器操作
     */
    static class VPOSHandler extends Handler {
        private final WeakReference<SwipeCard> mBaseActivity;

        public VPOSHandler(SwipeCard activity) {
            mBaseActivity = new WeakReference<SwipeCard>(activity);
        }

        public BaseActivity getActivity() {
            return mBaseActivity.get();
        }

        @Override
        public void handleMessage(Message msg) {
            final SwipeCard activity = (SwipeCard) getActivity();
            if (null == activity) {
                return;
            }
            int status = msg.getData().getInt("status");
            switch (status) {
                case ISwiperListener.Status_Swipe: {// 等待刷卡
                    HPLog.i("VPOSActivity", "等待刷卡-------------");
                    long startTime = SystemClock.elapsedRealtime();
                    View cardView;
                    HPLog.e("FDL", "---ApiSwiperFactory.getInstance().getSwiperModel()--"+ApiSwiperFactory.getInstance().getSwiperModel());
                    if (!ApiSwiperFactory.getInstance().getSwiperModel().mSupportSwiper) {
                        SwiperCardVoiceView swiperCardView2 = new SwiperCardVoiceView(activity, null);
                        swiperCardView2.setVisibility(1);
                        swiperCardView2.setIsSwiperOn(true);
                        swiperCardView2.setBackListener(new SwiperCardKLFActivity.BackListener() {
                            @Override
                            public void back() {
                                activity.goBack();
                            }
                        });
                        cardView = swiperCardView2;
                    } else {
                        activity.mSwiperCardView = new SwiperCardBluetoothView(activity, null);
                        HPLog.i("VPOSActivity",
                                "new SwiperCardView: "
                                        + (SystemClock.elapsedRealtime() - startTime));
                        cardView = activity.mSwiperCardView;
                    }
                    HPLog.i("VPOSActivity", "new SwiperCardView: " + (SystemClock.elapsedRealtime() - startTime));
                    if (0 != activity.llContent.getChildCount()) {
                        activity.llContent.removeAllViews();
                    }
                    HPLog.i("VPOSActivity", "remove : " + (SystemClock.elapsedRealtime() - startTime));
                    activity.llContent.addView(cardView);
                    HPLog.i("VPOSActivity", "addView : " + (SystemClock.elapsedRealtime() - startTime));
                    break;
                }
            }
        }
    }

    protected void refreshStatus(int status)
    {
        HPLog.e("refreshStatus", "" + status);
        Bundle data = new Bundle();
        data.putInt("status",status);
        Message msg = new Message();
        msg.setData(data);
        hRefreshStatus.sendMessage(msg);
    }
    private AlertDialog mSelectICApp;
    @Override
    public void showSelectICApp(final ArrayList<String> availableName,
                                final IICSelectApplicationCallback selectApplicationCallback) {
        if (0 == availableName.size()) {
            //提醒没得选择
            showNoAvailableApp(new Runnable() {
                @Override
                public void run() {
                    selectApplicationCallback.onCardTypeSelect(-1);
                }
            });
        } else if (1 == availableName.size()) {
            //只有一个可以选择，帮助用户选择
            selectApplicationCallback.onCardTypeSelect(0);
        } else {
            AlertDialog.Builder ab = new AlertDialog.Builder(SwipeCard.this);
            ab.setCancelable(false);
            ab.setAdapter(new ArrayAdapter<String>(SwipeCard.this,
                    R.layout.simple_list_item, availableName),new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    selectApplicationCallback.onCardTypeSelect(i);
                }
            });
            ab.setTitle(R.string.please_select_card_type);
            mSelectICApp = ab.create();
            mSelectICApp.show();
        }
    }

    @Override
    public void showNoAvailableApp(final Runnable r) {
        this.showAlertDialog(this, getString(R.string.tip_title),getString(R.string.no_available_card),
                false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        r.run();
                    }
                });
    }

    @Override
    public void closeSelectICApp() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mSelectICApp != null) {
                        HPLog.i("", "actually dismiss mSelectICApp dialog");
                        mSelectICApp.dismiss();
                        mSelectICApp = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mSelectICApp = null;
                }
            }
        });
    }

    @Override
    protected void goBack() {
        if (!this.isFinishing()) {
            clearFactor();
            stopAdpu();
            super.goBack();
        } else {
            HPLog.i("VPOSActivity", "ignore stopApdu");
        }
    }

    @Override
    protected void onDestroy()
    {
        if (mSwiperCardView != null)
        {
            mSwiperCardView.doDestroy();
            mSwiperCardView = null;
        }
        LandiSwiperBT.isSwiperCard = false;
        super.onDestroy();
    }
    @Override
    public void onSwiperStatus(int status, int result, String pan, boolean isDownlTrd)
    {
        super.onSwiperStatus(status, result, pan, isDownlTrd);
        HPLog.e("onSwiperStatus", status + " : " + result);
        if(result == ISwiperListener.Swiper_OK) {
        	if (ApiSwiperFactory.getInstance().getSwiperModel()== SwiperModel.P27_BLUETOOTH && isDownlTrd) {
				showAlertDialog(this, getString(R.string.tip), getString(R.string.text_ddt), false, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						doSwipe();
                        dialog.dismiss();
					}
				}, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						goBack();
                        dialog.dismiss();
					}
				});
				return;
			}
        	//刷卡成功。
        	Log.i("result", "pan="+pan);
            this.setResult(RESULT_OK, new Intent().putExtra(BaseProtocolKey.ACCOUNT, pan));
            HPLog.i(HPLog.YL_TAG, "SwipeCard close");
            goBack();
        } else if (ISwiperListener.Swiper_Cancel == result) {
            Toast.makeText(this, R.string.user_cancel, Toast.LENGTH_SHORT).show();
            goBack();
        } else if (ISwiperListener.Swiper_Timeout == result || ISwiperListener.Swiper_Error == result) {
            if(status == ISwiperListener.Status_Swipe) {
                showAlertDialog(this, getString(R.string.tip), getString(R.string.card_no_response), false,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doSwipe();
                                dialog.dismiss();
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                SwipeCard.this.onClick(null);
                            }
                        });
            }
        }
    }

    public void dealError() {
        showAlertDialog(this, "温馨提示", "刷卡器异常，请重试", false, new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                goBack();
            }
        });
    }

    public void stopSwiper() {
        goBack();
    }
}
